package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SoundService {
  /*  @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @DubboReference
    private StemApi stemApi;*/
  @Autowired
  protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

   @DubboReference
   private SoundApi soundApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private MessagesService messagesService;



    //发送语音
    public void sound(MultipartFile soundFile) throws IOException {
        if(soundFile.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }
        //上传语音到FastDFS中
        String filename = soundFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),soundFile.getSize(),filename,null);
        String soudUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        Sound  sound = new Sound();
        sound.setUserId(UserHolder.getUserId());
        sound.setSoundUrl(soudUrl);
        sound.setDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        //调用dubbo层添加语音的方法
        ObjectId soundId = soundApi.save(sound);

        if(soundId == null){
            throw new BusinessException(ErrorResult.iddErro());
        }
    }
    //接收语音
    public SoundVo reception() {
        //根据当前登录用户id查询Stem中所有数据
        List<Sound> soundList = soundApi.findBySids(UserHolder.getUserId());
        //获取redisKey
        String rediskey = Constants.STEM_kEY + UserHolder.getUserId();
        //获取redisvolue
        String redisValue = redisTemplate.opsForValue().get(rediskey);
        //redisvalue为空的话，给他一个key和value
        if (redisValue == null) {
            redisTemplate.opsForValue().set(Constants.STEM_kEY + UserHolder.getUserId(), "10");
        }
            //根据所有Stem数据查询出所有的sid
            List<Long> sidList = CollUtil.getFieldValues(soundList, "sid", Long.class);
            //判断sid数据是否为空
            if (CollUtil.isEmpty(sidList)) {
                return null;
            }

            int random = RandomUtils.nextInt(0, sidList.size() - 1);
            Sound sound = soundApi.queryStem(Long.valueOf(sidList.get(random)));
            UserInfo userInfo = userInfoApi.findById(sound.getUserId());
            String num = redisTemplate.opsForValue().get(Constants.STEM_kEY + UserHolder.getUserId());
            SoundVo vo = new SoundVo();
            if (Long.valueOf(num) > 0) {
                vo.setId(sound.getUserId());
                vo.setAge(userInfo.getAge());
                vo.setGender(userInfo.getGender());
                vo.setNickname(userInfo.getNickname());
                vo.setSoundUrl(sound.getSoundUrl());
                vo.setAvatar(userInfo.getAvatar());
                vo.setRemainingTimes(Integer.parseInt(num));
                redisTemplate.opsForValue().set(Constants.STEM_kEY + UserHolder.getUserId(), String.valueOf(Long.valueOf(num) - 1));
            } else {
                throw new BusinessException(ErrorResult.notErro());
            }
        //1、调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserId(), sound.getUserId(), true);
        if(!save) {
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        if(isLike(sound.getUserId(),UserHolder.getUserId())) {
            //4、添加好友
            messagesService.contacts(sound.getUserId());
        }
        return vo;

    }
    public Boolean isLike(Long userId,Long likeUserId) {
        String key = Constants.USER_LIKE_KEY+userId;
        return redisTemplate.opsForSet().isMember(key,likeUserId.toString());
    }

    }
